import request from './request'

class OSSUploader {

  /**
   * 上传文件到OSS
   * @param {string} filePath - 本地文件路径
   * @param {string} filename - 原始文件名
   * @param {function} onProgress - 上传进度回调
   */
  async uploadFile(filePath, filename, onProgress = null) {
    try {
      // 1. 从服务端获取STS临时凭证
      // const stsData = await this.getSTSToken(filename);

      // if (stsData.code !== 200) {
      //   throw new Error('获取上传凭证失败: ' + stsData.msg);
      // }
      // "securityToken": "CAISwwJ1q6Ft5B2yfSjIr5qBHvjD35dtgPCqVx+Ik1AgRN1DmY2akDz2IHhMe3BrA+kctPwxlWtZ7f8clqZ0UIQAXlDfKNB99Y9W9gX52iMHdQTuv9I+k5SANTW5KXyShb3/AYjQSNfaZY3eCTTtnTNyxr3XbCirW0ffX7SClZ9gaKZ8PGD6F00kYu1bPQx/ssQXGGLMPPK2SH7Qj3HXEVBjt3gX6wo9y9zmmZ3MsEGD3Qyhl79P+tupGPX+MZkwZqUYesyuwel7epDG1CNt8BVQ/M909vccoWie5YvEWQMJvUTdYrGNrMcPJw94d6E8XrRULgcYd2vCaYY5/qaAKHYlVYk9O0y3z1AwTHE+dU2DgncopxuK2mVMozF+DOOBlykOTxwV+q1EtZQvVPF+JzKCBM+USMuFvGSuSGPF78BI/6i8j/IdpxqAAVmSqePYTihAizOCOA317UDfBpCNhD9+z3V2tYEaiJSasS4CK8OKvHcmR58Hhd8Lk9VXVNvTPw21zhIwWHa8mtjPXJDe8XOoE53FjltS8TZRcywIgKR2a/wXsO20HRkQ9JDerH+zIV1A7RCWbmLKPYIr47NyUby83oH4wY1vSFZeIAA=",
      //   "accessKeySecret": "8kgSxXrsRHP19PBK9LH8ZHsFoMfpXzJvMGRcnhapEdkK",
      //   "accessKeyId": "STS.NY4UBw2HL72AU99wPuHRovH1r",
      //   "expiration": "2025-10-21 11:24:05",
      //   "regionId": "cn-chengdu",
      //   "bucket": "chiyan",
      //   "endpoint": "https://oss-cn-chengdu.aliyuncs.com",
      //   "domain": "https://oss.ytsoft.cc"

      // const { credentials, region, bucket, endpoint, filePath: ossFilePath } = stsData.data;
      let credentials = {
        SecurityToken:'CAISwwJ1q6Ft5B2yfSjIr5ndGMr3nptx2KeIUxSDpTEYYtpogZ2f0Dz2IHhMe3BrA+kctPwxlWtZ7f8clqZ0UIQAXlDfKNB99Y9W9gX5oTBiewTuv9I+k5SANTW5KXyShb3/AYjQSNfaZY3eCTTtnTNyxr3XbCirW0ffX7SClZ9gaKZ8PGD6F00kYu1bPQx/ssQXGGLMPPK2SH7Qj3HXEVBjt3gX6wo9y9zmmZ3MsEGD3Qyhl79P+tupGPX+MZkwZqUYesyuwel7epDG1CNt8BVQ/M909vccoWie5YvEWQMJvUTdYrGNrMcPJw94d6E8XrRULgcYd2vCaYY5/qaAKHYlVYk9O0y3z7A9XV4edU2DgncopxuK2mVMozF+DOOBlykOTxwV+q1EtZQvVPF+JzKCBM+USMuFvGSuSGPF78BZWDVVj/IdpxqAARbrq56YAUqiC/tOTpZ3YUI1DFCvjrevSgg5h+0x79ZyaLMxu1zIrv31DA4xCZuymA9Snzjv2zzl6tRzrpV6sHYE4nLDjvxwi/WMHXsc3HZ6u8+mLYDFlsfbbzjmBVt0QxNyH+9MUUVNGJxi2nWvR2dJTLpGng823pxfPICg748fIAA=',
        AccessKeyId:'STS.NZhSpCsDPoecQ22A1MnUDnX42',
        AccessKeySecret:'4Ec4Zt4QViuzXronU8pVtkmg9kpAijDi9QG9FwtA9C28',
        policy:'eyJleHBpcmF0aW9uIjoiMjAyNS0xMC0yMVQwNDo0MDowNC45NzRaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCIiXV19',
        signature:'g9WOTSQJjkI4BlSU2anUszOpeZ4='
      };

      // 2. 执行上传
      const result = await this.uploadToOSS(
        filePath,
        'images/test/2025-10-21.png',
        credentials,
        'cn-chengdu',
        'chiyan',
        'https://chiyan.oss-cn-chengdu.aliyuncs.com',
        onProgress
      );
      console.log(result)

      return {
        success: true,
        url: `https://chiyan.oss-cn-chengdu.aliyuncs.com/images/test/2025-10-21.png`,
        filePath: 'images/test/2025-10-21.png'
      };

    } catch (error) {
      console.error('上传失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 获取STS临时凭证
   */
  async getSTSToken(filename) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://oss-cn-chengdu.aliyuncs.com/oss/sts-token`,
        method: 'GET',
        data: {
          filename: filename
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 上传文件到OSS
   */
  async uploadToOSS(filePath, ossFilePath, credentials, region, bucket, endpoint, onProgress) {
    return new Promise((resolve, reject) => {
      // 使用微信小程序的上传API
      wx.uploadFile({
        url: `https://chiyan.oss-cn-chengdu.aliyuncs.com`, // OSS endpoint
        filePath: filePath,
        name: 'file',
        formData: {
          'key': ossFilePath,
          'policy': credentials.policy,
          'OSSAccessKeyId': credentials.AccessKeyId,
          'signature': credentials.signature,
          'success_action_status': '200',
          'x-oss-security-token': credentials.SecurityToken
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res);
          } else {
            reject(new Error(`上传失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 选择并上传图片
   */
  async uploadImage(onProgress = null) {
    return new Promise((resolve, reject) => {
      // 选择图片
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const filename = `image_${Date.now()}.jpg`;

          try {
            const result = await this.uploadFile(tempFilePath, filename, onProgress);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 选择并上传视频
   */
  async uploadVideo(onProgress = null) {
    return new Promise((resolve, reject) => {
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: async (res) => {
          const tempFilePath = res.tempFilePath;
          const filename = `video_${Date.now()}.mp4`;

          try {
            const result = await this.uploadFile(tempFilePath, filename, onProgress);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 选择并上传文件
   */
  async uploadFileFromSystem(onProgress = null) {
    return new Promise((resolve, reject) => {
      wx.chooseMessageFile({
        count: 1,
        type: 'all',
        success: async (res) => {
          const tempFilePath = res.tempFiles[0].path;
          const filename = res.tempFiles[0].name;

          try {
            const result = await this.uploadFile(tempFilePath, filename, onProgress);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

// module.exports = OSSUploader;

export default OSSUploader;
